var http = require('http');
var url = require('url');
var querystring = require('querystring');

var __type = 'author';
var App = require('./App.js');
var app = App(__type, handle, function(err) {
	if (err) console.log(err);
});


var server = http.createServer(function(req, res) {
	console.log('get request');
	// handle(req, res);
	// benchmark1(req, res);
	var reqUrl = url.parse(req.url);
	var pathname = reqUrl.pathname;
	var qs = querystring.parse(reqUrl.query);
	var time = qs.time;
	console.log('benchmark2 %s', time);
	benchmark2(req, res, time);
});

server.listen(8080);
console.log('server start...');

var rpcClient = null;
server.type = 'authorHttp';

function handle(req, res) {
	app.rpc('book', 'hello,i am author', function(err, result) {
		if (err) return console.log(err);
		console.log(result.toString());
		res.end(result.toString());
	});
	// contrast with
	// request(url,function(err,res,body){ ... })
}


function benchmark1(req, res, times) {
	times = times || 1;
	var count = times;
	var start = new Date().getTime();

	function foo() {
		if (count === 0) {
			var cost = new Date().getTime() - start;
			console.log(times + ' request cost=' + cost)
			return res.end(times + ' request cost=' + cost + '\n');
		}
		app.rpc('book', 'a', function(err, result) {
			count--;
			foo();
		})
	}
	foo();
}


function benchmark2(req, res, times) {
	times = Number(times || 1);
	var finish = 0;
	var start = new Date().getTime();


	for (var i = 0; i < times; i++) {
		app.rpc('book', 'a', function(err, result) {
			finish += 1;
			console.log('rpc done one, finish = %s', finish);
			if (finish === times) {
				console.log('all rpc done, finish = %s', finish);
				var cost = new Date().getTime() - start;
				console.log(times + ' request cost=%s', cost);
				res.end(times + ' request cost=' + cost + '\n');
			}
		});
	}
}